var express = require('express');
var router = express.Router();

const multer = require("multer");
const fs = require("fs");
const path = require('path');

const upload = multer({
  dest:"message"
});

/* GET users listing. */
router.get('/', function(req, res, next) {
  // res.send('respond with a resource');
  res.locals.user = req.session.user || "";
  res.locals.list = msg_arr;
  res.render("work");
});

var users = {};

var msg_arr = [];

router.post("/login", function(req, res) {
  const {loginname,password} = req.body;
  if ( users[loginname] && ( users[loginname].password = password ) ) {
    req.session.user = {loginname}
    res.locals.user = req.session.user;
  }else {
    res.send( "账号密码不存在" );
  }
   res.redirect("/work");
});

router.post("/reg", function(req, res) {
  const {loginname,password,confirm} = req.body;
  if (loginname && password && password === confirm) {
    users[loginname] = {loginname,password};
    res.locals.user = req.session.user;
  }
  else {
    res.send( "注册失败" );
  }
  res.redirect("/work");
})

router.get("/logout", function(req, res) {
  req.session.user = undefined;
  res.redirect("/work");
});

router.get("/to_login",function(req,res) {
  res.render("work_login");
})

router.get("/to_reg",function(req,res) {
  res.render("work_reg");
})

router.post("/message",function (req,res) {
  var msg_user = {};
  var date = new Date().toLocaleDateString();
  var time = new Date().toLocaleTimeString();

  var name = req.session.user.loginname + ' ' + date + '_' + time;
  var message = req.body.message;
  msg_user = {name,message}

  var msg_txt = name + '-' + message + ';';
  fs.appendFile(path.join(__dirname, '../message/msg.txt'), msg_txt ,function(err){
    console.log(err);
  })

  msg_arr.push(msg_user);

  res.redirect("back");
})

module.exports = router;
